<?php

declare(strict_types=1);

use App\ApplicationParams;
use Yiisoft\Html\Html;
use Yiisoft\Router\UrlGeneratorInterface;
use Yiisoft\View\WebView;

/**
 * @var WebView $this
 * @var ApplicationParams $applicationParams
 * @var UrlGeneratorInterface $urlGenerator
 * @var array{id:int,token:string,label:?string,response_status:int,response_content_type:string,response_headers:string,response_body:string,created_at:string,last_accessed_at:?string} $webhook
 * @var list<array{id:int,method:string,path:string,created_at:string}> $requests
 * @var array{id:int,webhook_id:int,method:string,scheme:string,host:string,path:string,query_params:array<string,mixed>,headers:array<string,list<string>>,body:?string,ip_address:?string,user_agent:?string,created_at:string}|null $selectedRequest
 * @var string $captureUrl
 * @var string|null $csrf
 */

$label = $webhook['label'] ?? null;
$this->setTitle($label === null ? 'Webhook ' . substr($webhook['token'], 0, 8) : $label);

$headersString = $webhook['response_headers'];
$displayLabel = $label === null ? '未命名' : $label;
$examplesUrl = rtrim($captureUrl, '/') . '/example-path';

$formatJson = static function (mixed $value): string {
    $encoded = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    return $encoded === false ? 'null' : $encoded;
};
?>

<div class="webhook-page">
    <section class="webhook-summary">
        <header>
            <div class="summary-title">
                <h1><?= Html::encode($displayLabel) ?></h1>
                <p class="token"><strong>Token:</strong> <code><?= Html::encode($webhook['token']) ?></code></p>
            </div>
            <div class="summary-meta">
                <dl>
                    <div>
                        <dt>创建时间</dt>
                        <dd><time datetime="<?= Html::encode($webhook['created_at']) ?>"><?= Html::encode($webhook['created_at']) ?></time></dd>
                    </div>
                    <div>
                        <dt>最近访问</dt>
                        <dd>
                            <?php if ($webhook['last_accessed_at'] !== null): ?>
                                <time datetime="<?= Html::encode($webhook['last_accessed_at']) ?>"><?= Html::encode($webhook['last_accessed_at']) ?></time>
                            <?php else: ?>
                                <span class="muted">尚未收到请求</span>
                            <?php endif; ?>
                        </dd>
                    </div>
                </dl>
                <div class="summary-actions">
                    <form class="inline-form" method="post" action="<?= Html::encode($urlGenerator->generate('webhook.delete', ['token' => $webhook['token']])) ?>">
                        <?php if ($csrf !== null): ?>
                            <?= $csrf->hiddenInput() ?>
                        <?php endif; ?>
                        <button type="submit" class="button button-danger">删除 Webhook</button>
                    </form>
                </div>
            </div>
        </header>

        <div class="capture-url">
            <h2>监听地址</h2>
            <p>将第三方回调指向下方地址以捕获请求：</p>
            <code class="url-block"><?= Html::encode($captureUrl) ?></code>
            <p class="secondary">可附加任意路径：<code><?= Html::encode($examplesUrl) ?></code></p>
        </div>

        <form class="response-form" method="post" action="<?= Html::encode($urlGenerator->generate('webhook.response.update', ['token' => $webhook['token']])) ?>">
            <?php if ($csrf !== null): ?>
                <?= $csrf->hiddenInput() ?>
            <?php endif; ?>
            <h2>自定义响应</h2>
            <p class="secondary">设置该 webhook 在收到请求时返回的内容。</p>
            <div class="form-grid">
                <label>
                    <span>HTTP 状态码</span>
                    <input type="number" name="status" min="100" max="599" value="<?= Html::encode((string) $webhook['response_status']) ?>" required>
                </label>
                <label>
                    <span>Content-Type</span>
                    <input type="text" name="content_type" value="<?= Html::encode($webhook['response_content_type']) ?>" required>
                </label>
            </div>
            <label>
                <span>响应头（每行“Header: Value”）</span>
                <textarea name="headers" rows="3" placeholder="X-Debug: yes"><?= Html::encode($headersString) ?></textarea>
            </label>
            <label>
                <span>响应正文</span>
                <textarea name="body" rows="8" placeholder='{"ok":true}'><?= Html::encode($webhook['response_body']) ?></textarea>
            </label>
            <button type="submit">保存设置</button>
        </form>
    </section>

    <section class="webhook-requests">
        <header class="section-header">
            <div>
                <h2>请求日志</h2>
                <p class="secondary">展示最近 50 条调用记录。</p>
            </div>
            <?php if ($requests !== []): ?>
                <form class="inline-form" method="post" action="<?= Html::encode($urlGenerator->generate('webhook.requests.clear', ['token' => $webhook['token']])) ?>">
                    <?php if ($csrf !== null): ?>
                        <?= $csrf->hiddenInput() ?>
                    <?php endif; ?>
                    <button type="submit" class="button button-secondary">清空请求日志</button>
                </form>
            <?php endif; ?>
        </header>

        <?php if ($requests === []): ?>
            <div class="empty-state">
                <p>还没有收到任何请求。使用上方地址尝试发送一个吧。</p>
            </div>
        <?php else: ?>
            <div class="requests-grid">
                <ul class="request-list">
                    <?php foreach ($requests as $requestRow): ?>
                        <?php
                        $isActive = $selectedRequest !== null && $selectedRequest['id'] === $requestRow['id'];
                        $requestUrl = $urlGenerator->generate(
                            'webhook.show',
                            ['token' => $webhook['token']],
                            ['request' => (string) $requestRow['id']],
                        );
                        ?>
                        <li class="<?= $isActive ? 'active' : '' ?>">
                            <a href="<?= Html::encode($requestUrl) ?>">
                                <span class="badge"><?= Html::encode($requestRow['method']) ?></span>
                                <span class="path"><?= Html::encode($requestRow['path']) ?></span>
                                <time datetime="<?= Html::encode($requestRow['created_at']) ?>"><?= Html::encode($requestRow['created_at']) ?></time>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>

                <div class="request-details">
                    <?php if ($selectedRequest === null): ?>
                        <div class="empty-state">
                            <p>选择左侧任意请求查看详情。</p>
                        </div>
                    <?php else: ?>
                        <article>
                            <header>
                                <h3><?= Html::encode($selectedRequest['method']) ?> <?= Html::encode($selectedRequest['path']) ?></h3>
                                <time datetime="<?= Html::encode($selectedRequest['created_at']) ?>"><?= Html::encode($selectedRequest['created_at']) ?></time>
                                <?php if ($selectedRequest['ip_address'] !== null): ?>
                                    <p class="secondary">来源 IP：<?= Html::encode($selectedRequest['ip_address']) ?></p>
                                <?php endif; ?>
                                <?php if ($selectedRequest['user_agent'] !== null): ?>
                                    <p class="secondary">User-Agent：<?= Html::encode($selectedRequest['user_agent']) ?></p>
                                <?php endif; ?>
                            </header>

                            <section>
                                <h4>查询参数</h4>
                                <pre><?= Html::encode($formatJson($selectedRequest['query_params'])) ?></pre>
                            </section>

                            <section>
                                <h4>请求头</h4>
                                <pre><?= Html::encode($formatJson($selectedRequest['headers'])) ?></pre>
                            </section>

                            <section>
                                <h4>请求正文</h4>
                                <pre><?= Html::encode($selectedRequest['body'] ?? '') ?></pre>
                            </section>
                        </article>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </section>
</div>
